<template>
	<div id="clue_enroll_confirm" class="container">
		<div class="title">
			<span v-if="clue.name == '续费'">续费</span>
			<span v-else>报名</span>

			<!--（{{clue.realName}}）-->
			<div class="close" @click="cancel()"></div>
		</div>

		<div class="content">
			<div class="info">
				<div class="label">孩子姓名：</div>
				<div class="value" style="font-size: 0.18rem;">{{ clue.realName }}</div>
				<div class="label">联系人：</div>
				<div class="value">{{ parentName }}</div>
				<div class="label">联系电话：</div>
				<div class="value">{{ parentPhone }}</div>
			</div>
			<div class="table">
				<div class="thead">
					<div style="width: 0.6rem;"></div>
					<div style="width: 1.8rem;">名称</div>
					<div>总价</div>
					<div>单价</div>
					<div>购买数量</div>
					<div>单位</div>
					<div>合计金额</div>
					<div>应收金额</div>
				</div>
				<div class="tr_div" v-for="(item, index) in countList">
					<div class="tr">
						<div style="width: 0.6rem;">
							<span class="type">{{ item.mode }}</span>
						</div>

						<div style="width: 1.8rem;" v-if="item.classId" class="tr_two_row">
							<div>{{ item.name }}</div>
							<div>{{ item.className ? item.className : '' }}</div>
						</div>
						<div style="width: 1.8rem;" v-else>{{ item.name }}</div>

						<div>￥{{ item.price }}</div>

						<div>
							<template v-if="item.unitPrice">
								￥{{ item.unitPrice }}
							</template>
						</div>
						<div>{{ item.buyNum }}</div>
						<div>{{ item.unit }}</div>
						<div>￥{{ item.sumPrice }}</div>
						<div>￥{{ item.money }}</div>
					</div>
				</div>
			</div>

			<div class="count">
				<div>总计应收：￥{{ param.totalMoney }}</div>
				
				<!--<br v-if="coupon" />-->
				<template v-for="item in couponList">
					<br />
					<div class="reduce" @click="checkCoupon(item)">
						<span class="earnest_check" :class="coupon == item ? 'earnest_check_active' : ''"></span>
						<span :style="{ color: (coupon == item ? '#333333' : '#999999') }">
							{{couponTypeMap[item.couponType]}}（{{item.couponName}}）：
							
							<template v-if="item.couponType==1">
								{{item.couponValue}}折
							</template>
							<template v-else>
								-￥{{item.couponValue}}
							</template>
						</span>
					</div>
				</template>
				
				<br v-if="clue.earnestMoney != 0" />
				<div class="earnest" @click="checkEarnest()" v-if="clue.earnestMoney != 0">
					<span class="earnest_check" :class="param.useEarnestMoney == 1 ? 'earnest_check_active' : ''"></span>
					<span :style="{ color: param.useEarnestMoney == 1 ? '#333333' : '#999999' }">抵扣订金：-￥{{earnestMoney}}</span>
					<!--<span v-show="param.useEarnestMoney==1">剩余订金：￥{{clue.earnestMoney-param.earnestMoney}}</span>-->
				</div>
				<br />
				<div class="real_money clue-enroll-confirm-realMoney">
					应实收：
					<!-- <span>￥{{ param.realMoney }}</span> -->
					<span>￥</span>
					<el-input-number v-model="param.realMoney" :precision="2" style="width:2.5rem;"
					 :min="0" :max="preRealMoney" :controls="false" @change="alterRealMoney">
					 </el-input-number>
				</div>
			</div>

			<div class="title_sub">
				<span>*</span>
				支付方式
			</div>
			<div>
				<div class="radio_group">
					<label class="radio" v-for="(item, index) in payType" @click="clickPayType(item.value)">
						<span class="radio_circle" :class="item.value == payMode ? 'radio_active' : ''"></span>
						<span class="radio_name">{{ item.name }}</span>
					</label>
				</div>
			</div>

			<div class="title_sub">
				<span>*</span>
				实际报名时间(交易时间)
			</div>
			<div>
				<div class="radio_group">
					<el-date-picker
						v-model="enrollDate"
						value-format="yyyy-MM-dd HH:mm:ss"
						type="date"
						placeholder="选择日期">
					</el-date-picker>
				</div>
			</div>

			<div class="title_sub">
				<span></span>
				关联业务
			</div>
			<div class="row">
				<label class="label_2">
					<span>*</span>
					合同号
				</label>
				<el-input v-model="param.orderNo" id="orderNo" style="width:2.7rem;"
						  :disabled="!isContract" clearable maxLength="20"></el-input>
				<label class="contract" @click="checkContract()" :class="isContract ? '' : 'contract_check'">无合同</label>
			</div>
			<div>
				<label class="label_2">
					<span :style="'visibility:'+ (isMarkNessary?'visible':'hidden')">*</span>
					备注
				</label>
				<el-input v-model="remark" id="remark" style="width:10.4rem ;" maxLength="100" clearable></el-input>
			</div>
		</div>
		<div class="btn_div">
			<div class="btn_sure" @click="ok()">{{ sure_text }}</div>
			<div class="btn_cancel" @click="back()">上一步</div>
		</div>
	</div>
</template>

<script>
var vm, dict;

export default {
	data: function() {
		return {
			clue: {},
			countList: [],
			sure_text: '确认收款', //确认收款/去支付
			isContract: true, //是否有合同
			enrollDate:'',
			param: {
				orderNo: '', //订单号
				discount: null, //优惠金额
				useEarnestMoney: null, //是否使用定金
				earnestMoney: null, //定金金额
				totalMoney : null, //应付金额
				realMoney: null, //实际金额
				campusId: null //校区id
			},
			coupon: null, //使用的优惠券对象
			earnestMoney: null, //可以使用的订金
			payMode: null, //支付方式
			remark: '', //收据备注
			couponList: null, //优惠券
			//数据字典
			payType: null,
			couponTypeMap: null,
			isFirstPay: true, //是否是第一次进入支付页面
			savePayInfo: {},
			preRealMoney:0,//应该实际支付的金额
			isMarkNessary:false,//备注是否必须
		};
	},
	computed: {
		parentName: function() {
			var p = this.clue.parentData;
			return p&&p[0] ? p[0].parentName : null;
		},
		parentPhone: function() {
			var p = this.clue.parentData;
			return p&&p[0] ? p[0].phone : null;
		}
	},
	methods: {
		init: function(clue, countList) {
			vm.enrollDate=tool.DateToString(new Date(),"yyyy-MM-dd HH:mm:ss");
			//初始线索和结算列表数据
			vm.clue = clue;
			vm.countList = countList;

			//计算优惠,总金额
//			var discount = 0;
			//初始化默认值
			vm.isFirstPay = true;
			vm.savePayInfo = {};
			vm.isContract = true;
			vm.isMarkNessary=false;
			vm.remark = '';
			vm.param.discount = 0;
			vm.param.orderNo = '';
			vm.param.campusId = clue.campusId;
			vm.param.totalMoney = 0;
			//订金金额大于0时,默认使用订金
			vm.param.useEarnestMoney = clue.earnestMoney > 0 ? 1 : 0;
			
			//课程id
			var courseIds = '';
			
			var totalMoney = 0;
			countList.forEach(function(item) {
//				discount += item.discount;
				totalMoney += item.money;
				//拼接课程id
				courseIds += item.courseId ? ',' + item.courseId : '';
			});
			vm.param.totalMoney = parseFloat(totalMoney.toFixed(2));
//			vm.param.discount = discount;
			vm.payMode = vm.payType[0].value;
			
			//获取用户持有的优惠券
			var param = {
				needPayMoney: vm.param.totalMoney,
				orderSignupCourseIds: courseIds.substr(1),
				studentUserId: clue.studentUserId,
				campusId: clue.campusId
			};
			api.clueCouponList(param).then(function(data) {
				var coupon = null;
				var maxReduce = 0;
				data.data.forEach(function(item) {
					//计算优惠券减的钱
					if(item.couponType == 1) {
						//折扣券
						item.reduceMoney = vm.param.totalMoney * (10 - item.couponValue) * 0.1;
					} else {
						//满减券
						item.reduceMoney = item.couponValue;
					}
					//比较出最大的减钱
					if(item.reduceMoney > maxReduce) {
						coupon = item;
					}
				});
				//保存最优优惠券，优惠券列表
				vm.coupon = coupon;
				vm.couponList = data.data;
				
				vm.setMoney();
			});
			
		},
		/**
		 * 选择支付方式
		 */
		clickPayType(value) {
			var textMap = {
				1: '确认收款',
				2: '确认收款',
				3: '去支付',
				4: '去支付',
				5: "确认收款"
			};
			vm.payMode = value;
			vm.sure_text = textMap[value]||"确认收款";
		},
		setMoney: function() {
			//计算实际支付金额,使用订金金额
			var reduceMoney = (vm.coupon? vm.coupon.reduceMoney : 0);
			
			var p = vm.param;
			//学员订金和需要支付金额, 可支付订金取两者最小
			var a = vm.clue.earnestMoney;
			var b = p.totalMoney - reduceMoney;
			vm.earnestMoney = Math.min(a, b);
			vm.earnestMoney = parseFloat(vm.earnestMoney.toFixed(2));

			//实际交的订金
			p.earnestMoney = (p.useEarnestMoney == 0 ? 0 : vm.earnestMoney);
			//实际支付金额
			p.realMoney = p.totalMoney - p.earnestMoney - reduceMoney;
			p.realMoney=parseFloat(p.realMoney.toFixed(2));
			this.preRealMoney=p.realMoney;
		},
		alterRealMoney(val){
			if(this.preRealMoney!==val){
				this.isMarkNessary=true;
			}
			else{
				this.isMarkNessary=false;
			}
		},
		//提交报名数据
		ok: function() {
			//验证规则
			var rules = [{
					judge: !vm.isContract || vm.param.orderNo,
					focus: $('#clue_enroll_confirm #orderNo'),
					tips: '请输入合同号'
			}];
			if (!tool.validate(rules)) {
				return;
			}
			if(this.isMarkNessary){
				rules = [{
					judge: vm.remark,
					focus: $('#clue_enroll_confirm #remark'),
					tips: '请输入备注'
				}];
				if (!tool.validate(rules)) {
					return;
				}
			}
			if(!vm.enrollDate){
				this.$message({
					type:'warning',
					message:'实际报名时间不可为空！'
				});
				return;
			}
			
				
			if (!vm.isFirstPay) {
				
				let state = vm.sure_text == '确认收款' ? 2 : 1;
				if(vm.savePayInfo.info.orderSignupState != state){
					this.$message.error('该学员已报名，请勿选择其他支付方式');
					return;
				}
				vm.savePayInfo.info.orderNo = vm.param.orderNo;
				vm.savePayInfo.info.remark = vm.param.remark;
				vm.$emit('ok', vm.savePayInfo.countList, vm.savePayInfo.info);
			} else {
				var counts = vm.countList;

				var param = tool.clone(vm.param);
				param.clueId = vm.clue.clueId;
				param.campusId = vm.$store.state.campusId;
				param.remark = null;
				param.orderTime = vm.enrollDate;

				param.accountRecordData = [
					{
						payMode: vm.payMode, //支付方式
						receiptNo: null, //收据
						remark: vm.remark //收据备注
					}
				];

				//有折扣券，则加上折扣券的数据
				if (vm.coupon) {
					param.couponData = [{
						couponObtainId: vm.coupon.couponObtainId,
						couponId: vm.coupon.couponId
					}];
					param.discount = vm.coupon.reduceMoney;
				}

				//选课程,班级,商品列表
				param.courseData = [];
				param.goodsData = [];
				param.classData = [];
				let courseTotalMoney=0;
				for (var i = 0; i < counts.length; i++){
					var c = counts[i];
					if (c.type == '商品')continue;
					courseTotalMoney+=c.sumPrice;
				}
				for (var i = 0; i < counts.length; i++) {
					var c = counts[i];

					//修改金额按比例分配到每个课程,班级
					let alterMoney=vm.preRealMoney-param.realMoney;//手动修改金额
					let discountMoney=param.discount;//优惠券
					let earnestMoney=param.earnestMoney;//订金
					let totalReduce=alterMoney+discountMoney+earnestMoney;//总的减少金额
					let percent=c.sumPrice/courseTotalMoney;
					let realMoney=parseFloat((c.money-totalReduce*percent).toFixed(2));
					
					if (c.type == '商品') {
						param.goodsData.push({
							goodsId: c.id,
							goodsNum: c.buyNum,
							goodsOneMoney: c.unitPrice,
							totalMoney: c.sumPrice,
							realMoney: c.money
						});
					}
					if (c.type == '课程') {
						param.courseData.push({
							coursePackageId: c.packId,
							courseHour: c.buyNum,
							courseMoney: c.sumPrice,
							courseName: c.name,
							discountMoney: c.discount,
							realMoney: realMoney<0?0:realMoney
						});
					}
					if (c.type == '班级') {
						param.classData.push({
							classId: c.classId,
							className: c.className,
							coursePackageId: c.packId,
							courseHour: c.buyNum,
							courseMoney: c.sumPrice,
							discountMoney: c.discount,
							realMoney: realMoney<0?0:realMoney,
							buyNum: c.hour
						});
					}
				}
				param.orderSignupState = vm.sure_text == '确认收款' ? 2 : 1;
				
				if (vm.clue.name == '续费') {
					//续费
					param.studentId = vm.clue.studentId;
					//判断课程是否已经存在,可以重复报课程
					//				for(let i =0;i<vm.clue.courseList.length;i++){
					//					let course = vm.clue.courseList[i];
					//					for(let j =0;j<param.courseData.length;j++){
					//						if(course.coursePackageId==param.courseData[j].coursePackageId){
					//							vm.$message({
					//					          message: course.courseName+'课程已经存在,请勿重复报课',
					//					          type: 'warning'
					//					        });
					//					        return;
					//						}
					//					}
					//				}
					//续费
					api.renew(param).then(function(data) {
						if (data.result == '操作成功') {
							var info = tool.clone(param);
							//当支付方式为支付宝或者微信时，进入二维码支付页面
							if (info.accountRecordData[0].payMode == 3) {
								info.payName = 'wxpay';
							} else if (info.accountRecordData[0].payMode == 4) {
								info.payName = 'alipay';
							}
							info.orderSigupId = data.orderSignup.orderSigupId; //订单ID
							info.orderPayState = data.orderSignup.orderPayState; //订单支付状态
							vm.isFirstPay = false; //调到支付或者是其他页面，再次进入将不会产生订单
							vm.savePayInfo = {
								countList: vm.countList,
								info: info
							};
							vm.$emit('ok', vm.countList, info);
							vm.$parent.refrestData();
						}
					});
				} else {
					//报名
					api.clueEnroll(param).then(function(data) {
						if (data.result == '操作成功') {
							var info = tool.clone(param);
							//当支付方式为支付宝或者微信时，进入二维码支付页面
							if (info.accountRecordData[0].payMode == 3) {
								info.payName = 'wxpay';
							} else if (info.accountRecordData[0].payMode == 4) {
								info.payName = 'alipay';
							}
							info.orderSigupId = data.orderSignup.orderSigupId; //订单ID
							info.orderPayState = data.orderSignup.orderPayState; //订单支付状态
							vm.isFirstPay = false; //调到支付或者是其他页面，再次进入将不会产生订单
							vm.savePayInfo = {
								countList: vm.countList,
								info: info
							};
							vm.$emit('ok', vm.countList, info);
						}
						if (data.result == '操作失败，学员已存在') {
							tool.message('学员已存在，无须再报名');
						}
					});
				}
			}
		},
		cancel: function() {
			vm.$emit('cancel');
			vm.isFirstPay = true;
		},
		back: function() {
			vm.$emit('back');
			vm.isFirstPay = true;
		},
		checkCoupon: function(coupon) {
			vm.coupon = (vm.coupon==coupon? null : coupon);
			vm.setMoney();
		},
		checkEarnest: function() {
			//是否使用定金
			vm.param.useEarnestMoney = (vm.param.useEarnestMoney == 1 ? 0 : 1);
			vm.setMoney();
		},
		checkContract: function() {
			vm.isContract = !vm.isContract;
			if (!vm.isContract) {
				vm.param.orderNo = '';
			}
		}
	},
	mounted: function() {},
	created: function() {
		vm = this;
		dict = tool.getItem(lsKey.dict, true);
		vm.payType = dict['pay_mode'];
		vm.couponTypeMap = tool.parseDict(dict['coupon_type']);
	}
};
</script>
<style scoped src="@/style/module/radio.css"></style>
<style scoped src="@/style/module/dialog.css"></style>
<style scoped src="@/style/module/table2.css"></style>
<style scoped>
.radio_group {
	color: #333333;
	font-size: 0.18rem;
	padding-left: 0.2rem;
	padding-bottom: 0.05rem;
}

.radio_circle {
	top: 0.01rem;
}

.tr > div,
.thead > div {
	width: 1.44rem;
}

.tr_two_row {
	padding-top: 0.05rem;
	line-height: 0.2rem;
}

.content {
	padding: 0 0.3rem;
}

.info {
	font-size: 0.14rem;
	line-height: 0.3rem;
	padding: 0.05rem 0 0.1rem 0;
	overflow: hidden;
}

.info > div {
	float: left;
}

.label {
	padding-right: 0.05rem;
	color: #666666;
}

.value {
	width: 1.9rem;
	height: 0.3rem;
	font-size: 0.16rem;
	color: #333333;
	letter-spacing: 0.01rem;
}

.type {
	margin-left: 0.1rem;
	display: inline-block;
	height: 0.2rem;
	line-height: 0.2rem;
	font-size: 0.12rem;
	background-color: #3885f8;
	color: white;
	border-radius: 0.05rem;
	padding: 0 0.05rem;
	margin-right: 0.03rem;
}

.count {
	padding: 0.1rem 0.1rem 0.1rem 0;
	/*margin-bottom: 0.05rem;*/
	text-align: right;
	line-height: 0.3rem;
	color: #333333;
	font-size: 0.18rem;
	border-bottom: 0.01rem solid #f3f6fc;
	overflow: hidden;
}

.count > div {
	float: right;
}

.reduce {
	font-size: 0.16rem;
	cursor: pointer;
}

.earnest {
	font-size: 0.16rem;
	cursor: pointer;
	/*margin-bottom: 0.08rem;*/
}

.earnest_check {
	display: inline-block;
	vertical-align: middle;
	width: 0.25rem;
	height: 0.25rem;
	background-size: 0.16rem;
	background-repeat: no-repeat;
	background-position: center;
	background-image: url(../../../assets/img/clue_manage/check_no.png);
	position: relative;
	bottom: 0.01rem;
}

.earnest_check_active {
	background-image: url(../../../assets/img/clue_manage/check_yes.png);
}

.real_money {
	padding-top: 0.08rem;
}

.real_money > span {
	font-size: 0.26rem;
	color: #fc7301;
}

.title_sub {
	font-size: 0.22rem;
	color: #333333;
	line-height: 0.6rem;
}

.title_sub span {
	display: inline-block;
	color: red;
	width: 0.2rem;
	position: relative;
	top: 0.02rem;
}

.row {
	margin-bottom: 0.1rem;
}

.label_2 {
	display: inline-block;
	width: 0.75rem;
	font-size: 0.16rem;
	color: #666666;
}

.label_2 > span {
	display: inline-block;
	color: red;
	width: 0.18rem;
	position: relative;
	top: 0.01rem;
}

.contract {
	margin-left: 0.1rem;
	display: inline-block;
	min-width: 0.75rem;
	padding-left: 0.22rem;
	font-size: 0.16rem;
	color: #666666;
	vertical-align: middle;
	background-size: 0.16rem;
	background-repeat: no-repeat;
	background-position: left center;
	background-image: url(../../../assets/img/clue_manage/check_no.png);
	cursor: pointer;
	user-select: none;
}

.contract_check {
	background-image: url(../../../assets/img/clue_manage/check_yes.png);
}
</style>
<style lang='scss'>
	.clue-enroll-confirm-realMoney {
		.el-input__inner {
			font-size: 0.26rem !important;
			color: #fc7301 !important;
		}
	}
</style>
